<template>
  <div class="nav_container">
    <div class="left">
      <div class="btn_wrap">
        <i @click="back(1)" class="iconfont icon-31fanhui1"></i>
        <i @click="back(2)" class="iconfont icon-31fanhui2"></i>
      </div>
    </div>
    <div class="middle">
      <div class="title_wrap">
        <h2 :class="{ active: isActive == 1 }" @click="handleNav(1)">首页</h2>
        <h2 :class="{ active: isActive == 2 }" @click="handleNav(2)">发现</h2>
        <h2 :class="{ active: isActive == 3 }" @click="handleNav(3)">音乐库</h2>
      </div>
    </div>
    <div class="right">
      <div class="input_wrap">
        <el-input
          @keyup.enter.native="toSearch(searchData.trim())"
          slot="reference"
          placeholder="搜索"
          v-model="searchData"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"> </i>
        </el-input>
      </div>
      <div slot="reference" class="user_cover">
        <el-image
          @click="showLogin = !showLogin"
          :src="
            userinfo.avatarUrl
              ? userinfo.avatarUrl
              : require('@/assets/img/youke.gif')
          "
          fit="cover"
        ></el-image>
        <transition name="el-fade-in-linear">
          <el-dialog
            :show-close="false"
            :visible.sync="showLogin"
            :modal="false"
            :modal-append-to-body="false"
            top="0"
          >
            <div v-show="showLogin" class="login_box">
              <div class="theme">
                <span class="iconfont icon-aixin"></span> 欢迎
              </div>
              <div
                v-if="loginStatus === 'false'"
                @click="toLogin"
                class="login"
              >
                <span class="iconfont icon-denglu"></span> 登录
              </div>
              <div v-if="loginStatus === 'true'" @click="logout" class="login">
                <span class="iconfont icon-tuichu"></span> 登出
              </div>
            </div>
          </el-dialog>
        </transition>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getLogin } from "@/util/userinfo.js";

export default {
  name: "Nav",

  data() {
    return {
      searchData: "",
      isActive: 1,
      showLogin: false,
    };
  },
  computed: {
    ...mapGetters("userInfo", [
      //个人信息
      "userinfo",
      //登录状态
      "loginStatus",
    ]),
  },
  created() {
    //自动登录
    this.getCookie();
  },

  mounted() {},
  watch: {
    $route(to, from) {
      if (to.path == "/home") {
        this.isActive = 1;
      } else if (to.path == "/found") {
        this.isActive = 2;
      } else if (to.path == "/libaray") {
        this.isActive = 3;
      }
      //  else if (to.path == "/login") {
      //   this.toLogin();
      // }
    },
  },
  methods: {
    handleNav(index) {
      if (index == 1) {
        this.$router.push("/home");
      } else if (index == 2) {
        this.$router.push("/found");
      } else {
        this.$router.push("/libaray");
      }
      this.isActive = index;
    },
    back(item) {
      if (item == 1) {
        this.$router.go(-1);
      } else {
        this.$router.go(1);
      }
    },
    //跳转到搜素详情
    toSearch(keyword) {
      if (keyword !== "") {
        this.$router.push("/searchHome/" + keyword);
      }
    },
    //跳转登录
    toLogin() {
      this.showLogin = false;
      this.$router.push("/login");
    },
    //设置cookie
    setCookie(c_name, c_pwd, exdays) {
      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      window.document.cookie =
        "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie =
        "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
    },
    //清除cookie
    clearCookie: function () {
      this.setCookie("", "", -1); //修改2值都为空，天数为负1天就好了
    },
    //退出登录
    logout() {
      this.$confirm("是否退出账号?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.showLogin = false;
          this.$router.push("/login");
          //清空用户信息
          this.$store.dispatch("userInfo/saveUserInfo", {});
          //清理用户登录状态
          this.$store.dispatch("userInfo/saveLoginStatus", "false");
          sessionStorage.setItem("loginStatus", "false");
          //清理本地信息
          sessionStorage.clear(
            "userinfo",
            "userPrivatePlayList",
            "userId",
            "cookie",
            "userLikeList"
          );
          this.clearCookie();
          //保存用户id
          this.$store.dispatch("userInfo/saveUserId", "");
          this.$message({
            type: "success",
            message: "退出成功!",
          });
        })
        .catch(() => {});
    },
    //自动登录
    async getCookie() {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split("="); //再次切割
          //判断查找相对应的值
          if (arr2[0] == "userName") {
            //  console.log(arr2[1])
            var username = arr2[1]; //保存到保存数据的地方
          } else if (arr2[0] == "password") {
            // console.log(arr2[1])
            var password = arr2[1];
          }
        }
        let { data } = await getLogin(username, password);
        if (data.code !== 200) {
          return;
        }
        // console.log(data);
        //保存用户信息
        this.$store.dispatch("userInfo/saveUserInfo", data.profile);
        sessionStorage.setItem("userinfo", JSON.stringify(data.profile));
        //保存用户登录状态
        this.$store.dispatch("userInfo/saveLoginStatus", "true");
        sessionStorage.setItem("loginStatus", "true");
        //保存用户id
        this.$store.dispatch("userInfo/saveUserId", data.profile.userId);
        sessionStorage.setItem("userId", data.profile.userId);
        //获取cookie
        sessionStorage.setItem("cookie", data.cookie);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.nav_container {
  height: 70px;
  //   background-color: #ddd;
  display: flex;
  .left {
    width: 25%;
    .btn_wrap {
      height: 100%;
      display: flex;
      align-items: center;
      padding: 0 30%;
      i {
        font-size: 18px;
        font-weight: bold;
        margin-right: 15px;
        padding: 10px;
        border-radius: 10px;
        transition: 0.4s;
      }
      i:hover {
        background-color: #ddd;
      }
      i:active {
        transform: scale(1.1);
      }
    }
  }
  .middle {
    font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
    flex: 1;
    // background-color: #fff;
    display: flex;
    justify-content: center;
    .title_wrap {
      cursor: pointer;
      width: 40%;
      display: flex;
      justify-content: space-around;
      align-items: center;
      h2 {
        padding: 10px;
        border-radius: 10px;
        transition: 0.4s;
      }
      h2:hover {
        background-color: #ddd;
      }
      h2:active {
        transform: scale(1.1);
        color: #335eea;
      }
    }
  }
  .right {
    width: 24%;
    // background-color: pink;
    display: flex;
    align-items: center;
    .input_wrap {
      text-align: center;
      margin-right: 10px;
      .el-input {
        width: 90%;
        i {
          line-height: 30px;
          padding: 0;
        }
      }
      /deep/ .el-input__inner {
        height: 30px;
        border: none;
        border-radius: 5px;
        background-color: #f2f2f4;
        color: cornflowerblue;
        font-weight: 600;
        // background-color: #e13e3e;
      }
    }
    .user_cover {
      cursor: pointer;
      width: 30px;
      height: 30px;
      position: relative;
      .el-image {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
      /deep/.el-dialog__wrapper {
        .el-dialog {
          .el-dialog__header {
            height: 0;
            padding: 0;
            margin: 0;
          }
          .el-dialog__body {
            padding: 0;
          }
        }
      }
      .login_box {
        // top: -5px;
        z-index: 66;
        top: 20px;
        right: -310px;
        position: absolute;
        width: 130px;
        height: 130px;
        background-color: #fff;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
        border-radius: 5px;
        font-weight: 600;
        font-size: 16px;
        text-align: center;
        div:hover {
          background-color: #eaeffd;
          color: #335eea;
        }
        .theme {
          height: 50px;
          line-height: 50px;
        }
        .login {
          line-height: 50px;
          height: 50px;
        }
      }
    }
  }
}
</style>